#include "engine.h"
#include "./scene/node.h"
#include "./physics/physics.h"
#include "./scene/node.h"
#include <iostream>
#include "log.h"

Engine::Engine()
{
    Log::print("init Carlos Engine");
}

/**
 * 增加一个节点到场景中
 */
Node *Engine::addNode(std::string uuid)
{
    auto it = _nodes.find(uuid);
    if (it != _nodes.end())
    {
        Log::print("Create an exception. If the old node " + uuid + " still exists, return directly");
        return it->second; // 返回找到的节点引用
    }
    Node *newNode = new Node(uuid);
    auto result = this->_nodes.insert(std::make_pair(uuid, newNode));
    Log::print("Created new node " + uuid);
    return result.first->second;
}
/**
 * 从场景中删除一个节点
 */
void Engine::delNode(std::string uuid)
{
    //  auto result =this->_nodes.erase(uuid);
    auto it = this->_nodes.find(uuid);
    if (it != this->_nodes.end())
    {
        this->_nodes.erase(it);         // 从 map 中移除
        Node *deletedNode = it->second; // 保存指针
        deletedNode->destroy(); //销毁
        delete deletedNode; // 手动释放内存
    }
}
/**
 * 获取一个节点
 */
Node *Engine::getNode(std::string uuid)
{
    auto it = _nodes.find(uuid);
    if (it != _nodes.end())
    {
        return it->second; // 返回找到的节点引用
    }
    throw std::out_of_range("cpp:Node with UUID " + uuid + " not found");
}
void Engine::cleanAllNode()
{
}

void Engine::openPhysics()
{
    this->_physics = new Physics();
    Log::print("open phyiscs syste ..");
}
void Engine::closePhysics()
{
    delete this->_physics;
    Log::print("close phyiscs system ..");
}

void Engine::update(float dt)
{
    if (this->_physics != nullptr)
    {
        this->_physics->update(dt);
    }
}

Engine::~Engine()
{
}
